<style lang="scss">
.ua-image {
  display: inline-block;
  position: relative;
  font-size: 0;
}
</style>

<template>
  <div class="ua-image">
    <el-image
      :alt="alt"
      :style="style"
      :src="source"
      :preview-src-list="[source]"
      fit="cover"
      hide-on-click-modal
      append-to-body
    >
      <template #error>
        <slot name="error" />
      </template>
      <template #placeholder>
        <slot name="placeholder" />
      </template>
    </el-image>
  </div>
</template>

<script lang="ts">
import { qiniuFullLink } from '@assets/utils/qiniu'
import { fileRead } from '@assets/utils/util'
import { computed, defineComponent, ref, watch } from 'vue'

export default defineComponent({
  name: 'UImage',
  props: {
    src: { type: [String, File], default: '' },
    alt: { type: String, default: '' },
    width: Number,
    height: Number,
    errorIconSize: { type: Number, default: 20 },
  },
  emits: {
    error: (e: Error) => e instanceof Error,
    load: (e: Event) => e instanceof Event,
  },
  setup(props) {
    const source = ref('')

    watch(
      () => props.src,
      (nv) => {
        if (nv instanceof File) {
          fileRead(nv, 'base64').then((base64) => {
            source.value = base64
          })
        } else {
          source.value = nv.length ? qiniuFullLink(nv) : ''
        }
      },
      { immediate: true }
    )

    const style = computed(() => {
      return {
        width: `${props.width}${import.meta.env.VITE_LENGTH_UNIT}`,
        height: `${props.height}${import.meta.env.VITE_LENGTH_UNIT}`,
      }
    })

    return { source, style }
  },
})
</script>
